package com.inspectionwork.common.base;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.inspectionwork.common.utils.appkit.ConfigKit;
import com.inspectionwork.common.utils.appkit.FirefightingiotKit;
import com.inspectionwork.support.model.RespEntity;
import com.inspectionwork.support.utils.json.JsonKeyEdit;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class BaseService {
    @Resource
    HttpServletRequest httpServletRequest;
    HttpResponse httpResponse;

    public List<?> toTimeStr(List<? extends Map> list, String datePattern) {
        for (Map map : list) {
            map.forEach((k, v) -> {
                if (v instanceof Timestamp) {
                    map.put(k, DateUtil.format(new Date(((Timestamp) v).getTime()), datePattern));
                }
            });
        }
        return list;
    }

    public Map<String, Object> toTimeStr(Map param, String datePattern) {
        param.forEach((k, v) -> {
            if (v instanceof Timestamp) {
                param.put(k, DateUtil.format(new Date(((Timestamp) v).getTime()), datePattern));
            }
        });
        return param;
    }

    public Map<String, Object> toTimeStr(Map param) {
        return toTimeStr(param, DatePattern.NORM_DATE_PATTERN);
    }

    public List<?> toTimeStr(List<? extends Map> list) {
        return toTimeStr(list, DatePattern.NORM_DATE_PATTERN);
    }

//    public IPage toTimeStr(IPage iPage, String datePattern) {
//        List list = iPage.getRecords();
//        iPage.setRecords(toTimeStr(list, datePattern));
//        return iPage;
//    }
//
//    public IPage toTimeStr(IPage iPage) {
//        return toTimeStr(iPage, DatePattern.NORM_DATE_PATTERN);
//    }

    //事务相关开始

    protected int batchCount = 1000;// 每批commit的个数

    @Resource
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 获取session
     *
     * @author <br>
     * @return session对象
     */
    public SqlSession getSqlSession() {
        return sqlSessionFactory.openSession(ExecutorType.BATCH, false);
    }

    /**
     * 获取request操作对象
     *
     * @return request操作对象
     */
    protected HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 获取request操作对象
     *
     * @return request操作对象
     */
    protected HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    /**
     * 获取session操作对象
     *
     * @return session操作对象
     */
    protected HttpSession getSession() {
        return getRequest().getSession();
    }


    public <A> A getMapper(SqlSession session, Class<A> type) {
        return session.getMapper(type);
    }

    public void commit(SqlSession session) {
        if (session != null) {
            session.commit();
            // 清理缓存，防止溢出
            session.clearCache();
        }
    }

    public void rollback(SqlSession session) {
        if (session != null)
            session.rollback();
    }

    public void closeSession(SqlSession session) {
        if (session != null)
            session.close();
    }
    /**
     * 大量数据批量插入
     *
     * @author <br>
     *
     */
    public class BigData {
        List<?> list = new ArrayList<>();

        public BigData(List<?> list) {
            this.list = list;
        }

        public int getNum() {
            return (int) Math.ceil(list.size() / (batchCount*1.0));
        }

        @SuppressWarnings("unchecked")
        public <TNT> TNT getData(int i) {
            return (TNT) list.subList(i * batchCount, ((i + 1) * batchCount) > list.size() ? list.size():(i + 1) * batchCount);
        }
    }

    //获取用户id
    public String getUserId(){
        return "1";
    }
    //获取部门id
    public String getDeptId(){
        return "1";
    }
    //获取机构id
    public String getOrgId(){
        return "1";
    }

    // rest调用包装开始----------------------------------------------------------------------------------------------------------------------------

    //一企一档
    public RespEntity business(JSONObject jsonParam, String key, String gp){
        String ip = ConfigKit.getStr("businessJava","config");
        String methodPath = FirefightingiotKit.getStr(key,gp);
        String domain = ip + methodPath;
        String xml = "";
        if(httpServletRequest.getMethod().equalsIgnoreCase("GET")){
            xml = HttpUtil.get(domain,jsonParam);
        }else if(httpServletRequest.getMethod().equalsIgnoreCase("POST")){
            xml = HttpUtil.post(domain,jsonParam);
        }
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if(jsonObject.getInteger("code")==1){
            return RespEntity.fail(jsonObject.getString("msg"));
        }
        if(httpServletRequest.getMethod().equalsIgnoreCase("GET")){
            if(jsonObject.get("data")==null){
                return RespEntity.success(jsonObject.get("data"));
            }
            else if(jsonObject.get("data") instanceof com.alibaba.fastjson.JSONObject){
                return RespEntity.success(JSONUtil.parseObj(JsonKeyEdit.jsonKeyEdit(jsonObject.getJSONObject("data").toJSONString())));
            }else{
                return RespEntity.success(JSONUtil.parseArray(JsonKeyEdit.jsonKeyEdit(jsonObject.getJSONArray("data").toJSONString())));
            }
        }else{
            return RespEntity.success();
        }
    }

    //消防物联网
    public RespEntity fireFightingiot(JSONObject jsonParam, String configKey, String key, String gp){
        String ip = ConfigKit.getStr(configKey,"config");
        String methodPath = FirefightingiotKit.getStr(key,gp);
        String domain = ip + methodPath;
        String xml = "";
        if(httpServletRequest.getMethod().equalsIgnoreCase("GET")){
            xml = HttpUtil.get(domain,jsonParam);
        }else if(httpServletRequest.getMethod().equalsIgnoreCase("POST")){
            xml = HttpUtil.post(domain,jsonParam.toJSONString(1));
        }
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if(jsonObject.getInteger("code")==1){
            return RespEntity.fail(jsonObject.getString("msg"));
        }
        if(httpServletRequest.getMethod().equalsIgnoreCase("GET")){
            return RespEntity.success(jsonObject.get("data"));
        }else{
            return RespEntity.success();
        }
    }
    //消防物联网:token版本
    public RespEntity fireFightingiotForToken(JSONObject jsonParam, String configKey, String key, String gp){
        String ip = ConfigKit.getStr(configKey,"config");
        String methodPath = FirefightingiotKit.getStr(key,gp);
        String domain = ip + methodPath;
        String xml = "";
        if(httpServletRequest.getMethod().equalsIgnoreCase("GET")){
            httpResponse = HttpRequest.get(domain)
                    .header("Authorization", httpServletRequest.getHeader("Authorization"))
                    .form(jsonParam)
                    .execute();
        }else if(httpServletRequest.getMethod().equalsIgnoreCase("POST")){
            httpResponse = HttpRequest.post(domain)
                    .header("Authorization", httpServletRequest.getHeader("Authorization"))
                    .body(jsonParam.toJSONString(1))
                    .execute();
        }
        xml = httpResponse.body();
        int state = httpResponse.getStatus();
        if(state == 401) return RespEntity.expire();
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if(jsonObject.get("code")==null){//针对设备端的转发接口加的，它没有返回code
            return RespEntity.success();
        }
        if(jsonObject.getInteger("code")==1){
            return RespEntity.fail(jsonObject.getString("msg"));
        }
        if(httpServletRequest.getMethod().equalsIgnoreCase("GET")){
            return RespEntity.success(jsonObject.get("data"));
        }else{
            if(jsonObject.get("data")!=null){
                return RespEntity.success(jsonObject.get("data"));
            }
            return RespEntity.success();
        }
    }
    //消防物联网对接
    public RespEntity fireFightingiotTwo(JSONObject jsonParam, String configKey, String key, String gp){
        String ip = ConfigKit.getStr(configKey,"config");
        String methodPath = FirefightingiotKit.getStr(key,gp);
        String domain = ip + methodPath;
        String xml = "";
        if(httpServletRequest.getMethod().equalsIgnoreCase("GET")){
            xml = HttpUtil.get(domain,jsonParam);
        }else if(httpServletRequest.getMethod().equalsIgnoreCase("POST")){
            xml = HttpUtil.post(domain,jsonParam.toJSONString(1));
        }
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if(jsonObject.containsKey("Success") && !jsonObject.getBoolean("Success")){
            return RespEntity.fail(jsonObject.getString("Msg"));
        }
        if(jsonObject.containsKey("result") && !jsonObject.getBoolean("result")){
            return RespEntity.fail(jsonObject.getString("Msg"));
        }
        if(httpServletRequest.getMethod().equalsIgnoreCase("GET")){
            return RespEntity.success(jsonObject.get("data"));
        }else{
            return RespEntity.success(jsonObject);
        }
//        return RespEntity.success(jsonObject);
    }
    //消防物联网对接
    public RespEntity fireFightingiotTwo1(JSONArray jsonArray, String configKey, String key, String gp){
        String ip = ConfigKit.getStr(configKey,"config");
        String methodPath = FirefightingiotKit.getStr(key,gp);
        String domain = ip + methodPath;
        String xml = "";
       if(httpServletRequest.getMethod().equalsIgnoreCase("POST")){
            xml = HttpUtil.post(domain,jsonArray.toJSONString(1));
        }
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if(jsonObject.containsKey("Success") && !jsonObject.getBoolean("Success")){
            return RespEntity.fail(jsonObject.getString("Msg"));
        }
        if(jsonObject.containsKey("result") && !jsonObject.getBoolean("result")){
            return RespEntity.fail(jsonObject.getString("Msg"));
        }
        if(httpServletRequest.getMethod().equalsIgnoreCase("GET")){
            return RespEntity.success(jsonObject.get("data"));
        }else{
            return RespEntity.success(jsonObject);
        }
//        return RespEntity.success(jsonObject);
    }
    //组装数据：token版
    public com.alibaba.fastjson.JSONObject makeDataForToken(JSONObject jsonParam,String configKey,String configPg,String key,String gp){
        String ip = ConfigKit.getStr(configKey,configPg);
        String methodPath = FirefightingiotKit.getStr(key,gp);
        String domain = ip + methodPath;
        String xml = "";
        if(httpServletRequest.getMethod().equalsIgnoreCase("GET") || "getDecodeToken".equals(key) || "getAllArea".equals(key)){
            httpResponse = HttpRequest.get(domain)
                    .header("Authorization", httpServletRequest.getHeader("Authorization"))
                    .form(jsonParam)
                    .execute();
        }else if(httpServletRequest.getMethod().equalsIgnoreCase("POST")){
            httpResponse = HttpRequest.post(domain)
                    .header("Authorization", httpServletRequest.getHeader("Authorization"))
                    .body(jsonParam.toJSONString(1))
                    .execute();
        }
        xml = httpResponse.body();
        int state = httpResponse.getStatus();
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if(state == 401){
            com.alibaba.fastjson.JSONObject errorObject = new com.alibaba.fastjson.JSONObject();
            errorObject.put("methodCodeFlag","1");
            return errorObject;
        }
        else if(jsonObject.getInteger("code")==1){
            com.alibaba.fastjson.JSONObject errorObject = new com.alibaba.fastjson.JSONObject();
            errorObject.put("msg",jsonObject.getString("msg"));
            errorObject.put("methodErrorFlag","1");
            return errorObject;
        }

        return jsonObject.getJSONObject("data");
    }

    //组装数据
    public com.alibaba.fastjson.JSONObject makeData(JSONObject jsonParam,String configKey,String configPg,String key,String gp){
        String ip = ConfigKit.getStr(configKey,configPg);
        String methodPath = FirefightingiotKit.getStr(key,gp);
        String domain = ip + methodPath;
        String xml = "";
        httpResponse = HttpRequest.get(domain)
                .header("Authorization", httpServletRequest.getHeader("Authorization"))
                .form(jsonParam)
                .execute();
        xml = httpResponse.body();
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if(jsonObject.getInteger("code")==1){
            com.alibaba.fastjson.JSONObject errorObject = new com.alibaba.fastjson.JSONObject();
            errorObject.put("msg",jsonObject.getString("msg"));
            errorObject.put("methodErrorFlag","1");
            return errorObject;
        }
        return jsonObject.getJSONObject("data");
    }
    //组装数据:处理返回即可能是JSONObject又可能是JsonArray的情况
    public JSON makeDataForJSON(JSONObject jsonParam,String configKey,String configPg,String key,String gp){
        String ip = ConfigKit.getStr(configKey,configPg);
        String methodPath = FirefightingiotKit.getStr(key,gp);
        String domain = ip + methodPath;
        String xml = HttpUtil.get(domain,jsonParam);
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if(jsonObject.getInteger("code")==1){
            com.alibaba.fastjson.JSONObject errorObject = new com.alibaba.fastjson.JSONObject();
            errorObject.put("msg",jsonObject.getString("msg"));
            errorObject.put("methodErrorFlag","1");
            return errorObject;
        }
        return jsonObject.getJSONArray("data");
    }

    //组装数据:处理返回即可能是JSONObject又可能是JsonArray的情况:token版
    public JSON makeDataForJSONForToken(JSONObject jsonParam,String configKey,String configPg,String key,String gp){
        String ip = ConfigKit.getStr(configKey,configPg);
        String methodPath = FirefightingiotKit.getStr(key,gp);
        String domain = ip + methodPath;
        String xml = "";
        if(httpServletRequest.getMethod().equalsIgnoreCase("GET") || "getDecodeToken".equals(key) || "businessList".equals(key)){
            httpResponse = HttpRequest.get(domain)
                    .header("Authorization", httpServletRequest.getHeader("Authorization"))
                    .form(jsonParam)
                    .execute();
        }else if(httpServletRequest.getMethod().equalsIgnoreCase("POST")){
            httpResponse = HttpRequest.post(domain)
                    .header("Authorization", httpServletRequest.getHeader("Authorization"))
                    .body(jsonParam.toJSONString(1))
                    .execute();
        }
        xml = httpResponse.body();
        int state = httpResponse.getStatus();
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if(state == 401){
            com.alibaba.fastjson.JSONObject errorObject = new com.alibaba.fastjson.JSONObject();
            errorObject.put("methodCodeFlag","1");
            return errorObject;
        }
        else if(jsonObject.getInteger("code")==1){
            com.alibaba.fastjson.JSONObject errorObject = new com.alibaba.fastjson.JSONObject();
            errorObject.put("msg",jsonObject.getString("msg"));
            errorObject.put("methodErrorFlag","1");
            return errorObject;
        }
        return jsonObject.getJSONArray("data");
    }

// rest调用包装结束----------------------------------------------------------------------------------------------------------------------------

}
